package gov.nist.ssd.swqb.config;

import gov.nist.ssd.swqb.core.files.OptionManager;

public class RequestsTimeout {

    private static final String OPTION_STRING = "gov.nist.ssd.swqb.REQUESTS_TIMEOUT";
    private static boolean alreadyAccessedTimeoutValue = false;
    private static int timeoutValue = 1000;
    private static OptionManager optionManager;
    
    public static final String ERROR_MESSAGE = 
          "Timeout error !\n"
        + "You can change the timeout in the general options. Set it to 0 to desactivate the timeout.\n"
        + "Depending of your computer this error can be a bug, please contact xxxxx";

    private RequestsTimeout() {;
    }

    public static void setOptionManager(OptionManager o) {
        optionManager = o;
    }

    public static int requestsTimeout() {
        if (alreadyAccessedTimeoutValue) {
            return timeoutValue;
        } else { 
            String timeoutString = System.getProperty(OPTION_STRING);

            if (timeoutString != null) { //If argument is valide
                try {
                    timeoutValue = new Integer(timeoutString.trim());
                } catch (NumberFormatException e) {
                    System.err.println("Can't set timeout : '" + timeoutString + "' is not a valid number");
                }
            } else {
                //Search in the configuration file
                String timeout = optionManager.getOption("default_timemout");
                if (timeout != null) {
                    try {
                        timeoutValue = Integer.decode(timeout);
                    }
                    catch(Exception ex){
                        optionManager.setOption("default_timemout",Integer.toString(timeoutValue));
                        optionManager.save();
                    }
                }
            }

            alreadyAccessedTimeoutValue = true;
            return timeoutValue;
        }
    }

    public static void setRequestTimeout(int t) {
        timeoutValue = t;
    }
}
